const {decode} = require("../utils")
const moment = require("moment/moment");
const path = require("path");
const fs = require("fs");
const formidable = require("formidable");
module.exports = {
	cors(){
		return function(req,res,next){
			res.set("Access-Control-Allow-Origin","*");
			res.set("Access-Control-Allow-Headers","*");
			res.set("Access-Control-Allow-Methods","*");
			next();
		}
	},
	sendJson(){
		return function(req,res,next){
			res.sendJson = function(msg="网络连接错误",ok=-1){
				res.json({
					ok,
					msg
				})
			}
			next();
		}
	},
	author(){
		return (req,res,next)=>{
			// 获取到token
			decode(req.headers.token).then(()=>{
				next();
			}).catch(err=>{
				res.sendJson("token异常",-2)
			})
		}
	},
	uploadImg(){
		return function(req,res,next){
			// advPic
			res.uploadImg = function(picName){
				return new Promise((resolve,reject)=>{
					const datePath = moment().format("YYYY/MM/DD");
					const uploadDir = path.join(__dirname,"../../upload",datePath);
					if(!fs.existsSync(uploadDir)){
						fs.mkdirSync(uploadDir,{recursive:true});
					}
					const form = new formidable.IncomingForm({
						uploadDir,
						keepExtensions:true
					});
					form.parse(req,(err,params,file)=>{
						// 提交图片
						if(file[picName]){
							// 判断图片类型是否正确
							const advPic = file[picName][0];
							// 获取后缀名
							const extname = path.extname(advPic.filepath);
							const extArr = [".png", ".jpg", ".gif"];
							if (!extArr.includes(extname.toLowerCase())) {
								fs.unlinkSync(advPic.filepath);
								reject("请选择正确的图片类型，支持png,jpg,gif");
							}else{
								params[picName] = datePath + "/" + advPic.newFilename;
								resolve(params);
							}
						}else{
							// 未提交图片
							resolve(params);
						}
					})
				})
				
			};
			next();
			
			
			
		}
	}
}